#region Using

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration.Provider;
using System.IO;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using BlogEngine.Core;
using BlogEngine.Core.Providers;

#endregion

namespace BlogEngine.Core.StorageProviders
{
	public class MSSQLPhotoProvider : StorageProvider
	{
		private string _DatabaseName = "BlogEngine";

		/// <summary>
		/// Saves the specified photo.
		/// </summary>
		/// <param name="photo">The photo.</param>
		/// <param name="file">The file.</param>
		public override void Save(Photo photo, Stream file)
		{
			if (photo == null)
				throw new ArgumentNullException("photo");

			SQLManagedConnection myConn = new SQLManagedConnection(_DatabaseName);

			try
			{
				byte[] image = new byte[file.Length];

				file.Seek(0, SeekOrigin.Begin);
				file.Read(image, 0, (int)file.Length);

				myConn.GetTextCommand("INSERT INTO be_PhotoFiles (PhotoID, PhotoFile) VALUES (@id, @file)");
				myConn.AddInParameter("@id", DbType.Guid, photo.Id);
				myConn.AddInParameter("@file", DbType.Binary, image);
				myConn.ExecuteNonQuery();

				photo.Location = "[SQLProvider]";
			}
			finally
			{
				myConn.CloseIfNonTransactional();
			}
		}

		/// <summary>
		/// Updates the specified photo.
		/// </summary>
		/// <param name="photo">The photo.</param>
		/// <param name="file">The file.</param>
		public override void Update(Photo photo, Stream file)
		{
			Delete(photo);
			Save(photo, file);
		}

		/// <summary>
		/// Deletes the specified photo.
		/// </summary>
		/// <param name="photo">The photo.</param>
		public override void Delete(Photo photo)
		{
			if (photo == null)
				throw new ArgumentNullException("photo");

			SQLManagedConnection myConn = new SQLManagedConnection(_DatabaseName);

			try
			{
				myConn.GetTextCommand("DELETE FROM be_PhotoFiles WHERE PhotoID = @id");
				myConn.AddInParameter("@id", DbType.Guid, photo.Id);
				myConn.ExecuteNonQuery();
			}
			finally
			{
				myConn.CloseIfNonTransactional();
			}
		}

		/// <summary>
		/// Loads the specified photo.
		/// </summary>
		/// <param name="photo">The photo.</param>
		/// <returns></returns>
		public override Stream Load(Photo photo)
		{
			if (photo == null)
				throw new ArgumentNullException("photo");

			SQLManagedConnection myConn = new SQLManagedConnection(_DatabaseName);

			try
			{
				myConn.GetTextCommand("SELECT PhotoFile FROM be_PhotoFiles WHERE PhotoID = @id");
				myConn.AddInParameter("@id", DbType.Guid, photo.Id);

				byte[] storedImage = (byte[])myConn.ExecuteScalar();

				return new MemoryStream(storedImage);
			}
			finally
			{
				myConn.CloseIfNonTransactional();
			}
		}

	}
}

